<?php

class Inout extends CI_Controller
{

    public function Import()
    {
        $config['upload_path'] = './tmp/';
        $config['allowed_types'] = 'csv';

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload()) {
            $error = array('error' => $this->upload->display_errors());
            $error['msg'] = "Pozadovany typ suboru: CSV <br/><br/>";
            $this->load->view('templates/header.php');
            $this->load->view('pages/importCsv.php', $error);
            $this->load->view('templates/footer.php');
        } else {
            $data = array('upload_data' => $this->upload->data());
            $this->ImportData($data['upload_data']['full_path']);
            $error['msg'] = "<h3>Subor " . $data['upload_data']['file_name'] . " uspesne naimportovany do databazy. </h3>";
            $this->load->view('templates/header.php');
            $this->load->view('pages/importCsv.php', $error);
            $this->load->view('templates/footer.php');
        }


    }


    private function ImportData($data)
    {
        $fp = fopen($data, 'r');
        $jumpOverLine = false;
        while (!feof($fp)) {
            $line = fgetcsv($fp, null, ";");
            if (is_array($line)) {
                if ($jumpOverLine) {
                    $jumpOverLine = false;
                } else {
                    /*
                      * riesi bug s excelom = vymazava prazdne bunky v riadku
                    */
                    foreach ($line as $key => $value) {
                        if ($value == null) {
                            unset($line[$key]);
                        }
                    }

                    switch (sizeof($line)) {
                        case 1:
                            $jumpOverLine = true;
                            break;
                        case 2:
                            $this->parseBook($line);
                            break;
                        case 5:
                            $this->parseUser($line);
                            break;
                        case 7:
                            $this->parseTask($line);
                            break;

                    }
                }
            }

        }


        fclose($fp);

        unlink($data);
        $user_id = $this->session->userdata('id');
        $username = $this->session->userdata('firstname') . ' ' . $this->session->userdata('lastname');
        $this->log_model->addLog($user_id, $username . " -  import do databazy.");
    }

    private function parseTask($line)
    {
        $fk_books = $this->db->query(
            'SELECT id FROM books WHERE name = "' . $line[1] . '"'
        )->result_array();
        $newTask['name'] = $line[0];
        $newTask['fk_books'] = $fk_books[0]["id"];
        $newTask['x_units'] = $line[2];
        $newTask['y_units'] = $line[3];
        $newTask['description'] = $line[4];
        $newTask['page'] = $line[5];
        $newTask['functions_count'] = $line[6];


        //cekni, ci existuje riadok s rovnakym menom
        $res = $this->db->query('SELECT * FROM tasks WHERE name = "' . $newTask['name'] . '"')->result_array();
        if ($res == null) {
            //ak nie, vytvor
            $this->tasks_model->createTask(
                $newTask['name'],
                $newTask['fk_books'],
                $newTask['x_units'],
                $newTask['y_units'],
                $newTask['description'],
                $newTask['page'],
                $newTask['functions_count']);
        } else {
            //ak ano, updatni
            $this->db->where('name', $newTask['name']);
            $this->db->update('tasks', $newTask);
        }
    }

    private function parseBook($line)
    {
        $newBook['name'] = $line[0];
        $newBook['year'] = $line[1];

        //cekni, ci existuje riadok s rovnakym menom
        $res = $this->db->query('SELECT * FROM books WHERE name = "' . $newBook['name'] . '"')->result_array();
        if ($res == null) {
            //ak nie, vytvor
            $this->db->insert('books', $newBook);

        } else {
            //ak ano, updatni
            $this->db->where('name', $newBook['name']);
            $this->db->update('books', $newBook);
        }
    }

    private function parseUser($line)
    {
        $newUser['fk_roles'] = 1;
        $newUser['email'] = $line[0];
        $newUser['password'] = $line[1];
        $newUser['firstname'] = $line[2];
        $newUser['lastname'] = $line[3];
        $newUser['year'] = $line[4];


        //cekni, ci existuje riadok s rovnakym menom
        $res = $this->db->query('SELECT * FROM users WHERE email = "' . $newUser['email'] . '"')->result_array();
        if ($res == null) {
            //ak nie, vytvor
            $this->db->insert('users', $newUser);

        } else {
            //ak ano, updatni
            $this->db->where('email', $newUser['email']);
            $this->db->update('users', $newUser);
        }
    }

    private function prepareExportData()
    {
        $data['Knihy'] = array(
            array(
                0 => "Knihy"
            ),
            array(
                0 => "Nazov",
                1 => "Rocnik"
            )

        );
        $data['books'] = $this->books_model->listAll()->result_array();
        $data['Ulohy'] = array(
            array(
                0 => "Ulohy"
            ),
            array(
                0 => "Nazov",
                1 => "Ucebnica",
                2 => "os X",
                3 => "ox Y",
                5 => "Zadanie",
                6 => "Cislo strany",
                7 => "Rocnik"
            )

        );
        $data['tasks'] = $this->tasks_model->listAll()->result_array();
        $data['Uzivatelia'] = array(
            array(
                0 => "Uzivatelia"
            ),
            array(
                0 => "Email",
                1 => "Heslo",
                2 => "Meno",
                3 => "Priezvisko",
                5 => "Rocnik"
            )
        );
        $data['users'] = $this->db->query('SELECT * FROM users ')->result_array();

        //keby niekto nahodou chcel aj logy...
        //$data['log'] = $this->log_model->listAll("DESC")->result_array();

        //roles nema preco ucitel menit
        //$data['roles'] = $this->roles_model->listAll()->result_array();
        return $this->trimExportData($data);
    }

    private function trimExportData($data)
    {
        foreach ($data as $table_name => $rows) {
            // $data[$table_name][]["nazov_tabulky"] = $table_name;
            foreach ($rows as $row_id => $row) {
                foreach ($row as $column_name => $column_value) {
                    if ($column_name === "fk_roles" && $column_value == 2) {
                          unset ($data[$table_name][$row_id]);
                    } elseif ($column_name === "id" || $column_name === "fk_roles" || $column_name === "book_name") {
                        unset ($data[$table_name][$row_id][$column_name]);
                    } elseif ($column_name === "fk_books") {
                        $bookname = $this->db->query(
                            "SELECT name FROM books WHERE id =" . $column_value
                        )->result_array();
                        $data[$table_name][$row_id][$column_name] = $bookname[0]['name'];
                    }
                }

            }
        }
        return $data;
    }

    private function vypisExport($data)
    {
        foreach ($data as $table_name => $rows) {
            echo "========================" . "<br/>";
            echo $table_name . "<br/>";
            echo "========================" . "<br/>";
            foreach ($rows as $row_id => $row) {
                foreach ($row as $column_name => $column_value) {
                    echo $column_name . " = " . $column_value . "<br/>";
                }

            }
        }
    }


    public function Export()
    {
        $data = $this->prepareExportData();

        $filename ='exports/export.csv';
        $fp = fopen($filename, 'w');
        fwrite($fp,"\xEF\xBB\xBF"); // UTF-8 BOM - riesi problem s excelom
        foreach ($data as $table_name => $rows) {
            foreach ($rows as $row_id => $row) {
                fputcsv($fp, $row, ";");
            }
        }
        fclose($fp);

        $this->load->helper('download');
        $filecontents = file_get_contents($filename);
        force_download('export_' . date('Y-m-d_H-i-s', now() + 3600) . '.csv', $filecontents);

        $user_id = $this->session->userdata('id');
        $username = $this->session->userdata('firstname') . ' ' . $this->session->userdata('lastname');
        $this->log_model->addLog($user_id, $username . " -  export z databazy.");
    }

}

?>